package cn.com.ddapp.ddm.ui.mine;

import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hdos.usbdevice.publicSecurityIDCardLib;
import com.zhy.autolayout.AutoLinearLayout;

import java.io.UnsupportedEncodingException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.com.ddapp.ddm.AppConfig;
import cn.com.ddapp.ddm.R;
import cn.com.ddapp.ddm.api.OKUtilAPI;
import cn.com.ddapp.ddm.base.BaseActivity;
import cn.com.ddapp.ddm.base.BaseApplication;
import cn.com.ddapp.ddm.bean.Entity;
import cn.com.ddapp.ddm.inter.OkUtilCallback;
import cn.com.ddapp.ddm.util.SPUtils;
import cn.com.ddapp.ddm.util.TDevice;

public class CertificationActivityAtm extends BaseActivity {


    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.titletext)
    TextView titletext;
    @BindView(R.id.commit_certify)
    Button commitCertify;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.tv_bir)
    TextView tvBir;
    @BindView(R.id.tv_idcard)
    TextView tvIdcard;
    @BindView(R.id.ll)
    AutoLinearLayout ll;
    @BindView(R.id.img)
    ImageView img;
    private byte[] sex = new byte[6];
    private byte[] name = new byte[32];
    private byte[] birth = new byte[18];
    private byte[] nation = new byte[12];
    private byte[] address = new byte[72];
    private byte[] Department = new byte[32];
    private byte[] IDNo = new byte[38];
    private byte[] EffectDate = new byte[18];
    private byte[] ExpireDate = new byte[18];
    byte[] BmpFile = new byte[38556];
    private publicSecurityIDCardLib iDCardDevice;
    private Handler mHandler;
    boolean isstop = false;
    private String pkName;

    @Override
    public void initView() {
        pkName = this.getPackageName();
        titletext.setText(R.string.nameOk);
        iDCardDevice = new publicSecurityIDCardLib(CertificationActivityAtm.this);
        iDCardDevice = null;
        HandlerThread handlerThread = new HandlerThread("MyHandlerThread");
        handlerThread.start();
        mHandler = new Handler(handlerThread.getLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                switch (message.what) {
                    case 1001:
                        if (!isstop) {
                            mHandler.post(getdata);
                        }
                        break;
                    case 1002:
                        mHandler.removeCallbacks(getdata);
                        break;
                }
                return false;
            }
        });
        BaseApplication.showToast("请刷身份证。。。");
        mHandler.sendEmptyMessage(1001);
    }

    Runnable getdata = new Runnable() {
        @Override
        public void run() {
            getIdCardData();
        }
    };

    private void getIdCardData() {
        int ret;
        if (iDCardDevice == null) {
            iDCardDevice = new publicSecurityIDCardLib(mContext);
        }
        ret = iDCardDevice.readBaseMsgToStr(pkName, BmpFile, name, sex, nation, birth, address, IDNo, Department,
                EffectDate, ExpireDate);
        /********************************将图片放到textview里边显示****************************/
//		int[] colors =iDCardDevice.convertByteToColor(BmpFile);
//		b = Bitmap.createBitmap(colors, 102, 126, Bitmap.Config.ARGB_8888);
//		ImageSpan imgSpan = new ImageSpan(b);
//		SpannableString spanString = new SpannableString("icon");
//		spanString.setSpan(imgSpan, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        /**************************************************************************************/
        System.out.println("ret == " + ret);
        if (ret == 0x90) {
            mHandler.sendEmptyMessage(1002);
            int[] colors = iDCardDevice.convertByteToColor(BmpFile);
//                b = Bitmap.createBitmap(colors, 102, 126, Bitmap.Config.ARGB_8888);
//                names = new String(name, "Unicode");
//                sexs = new String(sex, "Unicode");
//                nations = new String(nation, "Unicode");
//                births = new String(birth, "Unicode");
//                addr = new String(address, "Unicode");
//                IDNos = new String(IDNo, "Unicode");
//                departments = new String(Department, "Unicode");
//                effectDates = new String(EffectDate, "Unicode");
//                departments = departments.replace(" ", "");
//                names = names.replace(" ", "");
//                sexs = sexs.replaceAll("[^\\u4e00-\\u9fa5]", "");
//                nations = nations.replaceAll("[^\\u4e00-\\u9fa5]", "");
//                addr = addr.replace(" ", "");
//                expireDates = new String(ExpireDate, "Unicode");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        img.setVisibility(View.GONE);
                        ll.setVisibility(View.VISIBLE);
                        commitCertify.setVisibility(View.VISIBLE);
                        tvName.setText("姓名：" + new String(name, "Unicode"));
                        tvSex.setText("性别：" + new String(sex, "Unicode"));
                        tvBir.setText("出生日期：" + new String(birth, "Unicode"));
                        tvIdcard.setText("身份证号：" + new String(IDNo, "Unicode"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            });
//				show = "姓名:"+new String(name, "Unicode")+'\n'
//						+"性别:"+new String(sex, "Unicode")+'\n'
//						+"民族:"+ new String(nation, "Unicode")+"族"+'\n'
//						+"出生日期:"+new String(birth, "Unicode")+'\n'
//						+"住址:"+new String(address, "Unicode")+'\n'
//						+"身份证号码:"+new String(IDNo, "Unicode")+'\n'
//						+"签发机关:"+new String(Department, "Unicode")+'\n'
//						+"有效日期:"+ new String(EffectDate, "Unicode") + "至" + new String(ExpireDate, "Unicode")+'\n';
        } else {
            mHandler.sendEmptyMessage(1001);
//			ToastUtil.ShowToast(mContext,"请将身份证放在识读区",200);
//			show ="读基本信息失败:"+String.format("0x%02x", ret);
        }
//		if(ret==0x90) viewBmp.setText(spanString);  			/*显示头像*/
    }

    @Override
    public void initData() {

    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_certification_atm;
    }

    @Override
    protected String getFragmentTag() {
        return null;
    }

    @OnClick({R.id.back, R.id.commit_certify})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.commit_certify:
                try {
                    saveNameAuth(new String(name, "Unicode"), new String(IDNo, "Unicode").trim());
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    private void saveNameAuth(String name, String idCard) {
        OkUtilCallback callback = new OkUtilCallback() {
            @Override
            public void onMyResponse(String response, int id) {
                Gson gson = new Gson();
                Entity entity = gson.fromJson(response, Entity.class);
                if ((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult())) && entity.getLogin()) {
                    BaseApplication.getIntstance().showToast("请检查网络", Toast.LENGTH_SHORT, 0, Gravity.CENTER);
                    if (TDevice.isTablet(getApplicationContext())) {
                        mHandler.sendEmptyMessage(1001);
                    }
                } else if ((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))) {
                    if (TDevice.isTablet(getApplicationContext())) {
                        mHandler.sendEmptyMessage(1001);
                    }
                    BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT, 0, Gravity.TOP);
                } else if ((AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))) {
                    BaseApplication.getIntstance().showToast("实名认证成功", Toast.LENGTH_SHORT, 0, Gravity.CENTER);
                    finish();
                }
            }
        };
        int ifATM = 0;
        if (TDevice.isTablet(getApplicationContext())) {
            ifATM = 1;//是ATM验证
        } else {
            ifATM = 0;
        }
        OKUtilAPI.post(OKUtilAPI.saveNameAuth, "userId=" + SPUtils.getStringData(this, SPUtils.USERID) + "&name=" + name + "&idcard=" + idCard + "&ifATM=" + ifATM, callback);
    }

    @Override
    protected void onStop() {
        super.onStop();
        isstop = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        isstop = false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (TDevice.isTablet(getApplicationContext())) {
            mHandler.removeCallbacks(getdata);
            mHandler.removeCallbacksAndMessages(null);
        }
    }

}
